package com.wy.panda.common.sign.validator;

import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

import com.wy.panda.common.sign.IValidator;
import com.wy.panda.common.sign.constant.AuthConstants;
import com.wy.panda.common.sign.constant.SignMethodEnum;
import com.wy.panda.common.sign.constant.Validator;
import com.wy.panda.common.util.SignatureUtils;
import com.wy.panda.exception.PandaAccessDeniedException;

import lombok.extern.slf4j.Slf4j;

/**
 * md5方式签名验证：
 * 
 * 形如：appSecret + signContent + appSecret
 * 
 * 例：
 * appSecret="123pkl"
 * 参数1：a="1"
 * 参数2：c="valy"
 * 参数3：b="val2"
 * 
 * 参数签名字符串为：a=1&b=val2&c=valy
 * 最终签名字符串为：123pkla=1&b=val2&c=valy123pkl
 * 
 * @author wangyuan
 * @since 2020年4月20日 下午6:09:55
 *
 */
@Slf4j
@Validator(signMethod = SignMethodEnum.MD5)
public class MD5Validator implements AuthConstants, IValidator {

	@Override
	public void validate(Map<String, String> params, String sign, String appSecret) {
		String signContent = SignatureUtils.getSignContent(params);
		signContent = appSecret + signContent + appSecret;
		log.debug("签名内容：{}", signContent);
		
		String serverGenerateSign = DigestUtils.md5Hex(signContent);
		log.debug("服务器生成的签名：{}", serverGenerateSign);
        if (!serverGenerateSign.equals(sign)) {
        	throw new PandaAccessDeniedException("Invalid signature");
        }
	}

}
